package cn.admin.configcenter.address;

import cn.admin.configcenter.configservice.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;

@RestController
public class AddressServer {

    private static final Logger LOGGER = LoggerFactory.getLogger(AddressServer.class);
    private static String serverListResponse;

    private static String generateServerListResponse(List<String> ipList) {
        StringBuilder sb = new StringBuilder();
        for (String ip : ipList) {
            sb.append(ip).append("\r\n");
        }

        return sb.substring(0,sb.length() - "\r\n".length());
    }

    @RequestMapping(
            value = {"/diamond-server/diamond", "/configserver/serverlist", "/vipserver/serverlist"},
            method = {RequestMethod.GET}
    )
    public String getServerList() {
        return serverListResponse;
    }

    @RequestMapping(
            value = {"/config-center/address-server/ip"},
            method = {RequestMethod.GET}
    )
    public String getIpAddress(HttpServletRequest request) {
        String ipAddress = request.getHeader("x-forwarded-for");
        if (StringUtils.isBlank(ipAddress) || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }

        if (StringUtils.isBlank(ipAddress) || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }

        if (StringUtils.isBlank(ipAddress) || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals("127.0.0.1")) {
                ipAddress = AddressServerIpHolder.getAddressServerIp();
            }
        }

        if (!StringUtils.isBlank(ipAddress) && ipAddress.length() > 15 && ipAddress.indexOf(",") > 0) {
            ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
        }

        return generateServerListResponse(Collections.singletonList(ipAddress));
    }

    static {
        List<String> serverList =
                Collections.singletonList(AddressServerIpHolder.getAddressServerIp());
        LOGGER.info("Edas config-center server list : " + serverList);
        serverListResponse = generateServerListResponse(serverList);
        LOGGER.debug("serverListResponse : " + serverListResponse);
    }

}
